package gw.com.android.ui.me_concern;

import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.BuildConfig;
import com.gwtsz.gts2.hx.R;

import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.PhoneLoginPresenter;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.MyConcernRequest;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.onlive.VipDialog;
import gw.com.android.utils.CacheUtils;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.model.DataItemDetail;
import www.com.library.util.StringUtils;
import www.com.library.view.XRecyclerView;

/**
 * 我的关注Activity
 */
public class MyConcernActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    private String userId;
    private MyConcernRequest myConcernRequest;
    private List<AnalystData> analystDataList = new ArrayList<>();
    private List<String> analystNoList = new ArrayList<>();//用来保存批量关注的analystNo
    private MyConcernRecyclerViewAdapter adapter;
    private boolean ifFirstLoadDataFinished = false;

    @BindView(R.id.recycler_view)
    XRecyclerView recycler_view;
    @BindView(R.id.rl_notice_tip)
    RelativeLayout mTip;
    @BindView(R.id.iv_close)
    ImageView mTipClose;
    @BindView(R.id.btn_open)
    Button mTipOpen;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_myconcern;
    }

    @Override
    protected void initLayoutView() {
        //公共标题栏初始化
        mTitleBar.setAppTitle(R.string.button_my_concern);
        //RecyclerView列表
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);// 布局管理, 默认纵向的，
        recycler_view.setLayoutManager(linearLayoutManager);//设置RecyclerView 布局
        recycler_view.hideFooter();
        recycler_view.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initViewData();
            }

            @Override
            public void onLoadMore() {
                recycler_view.loadMoreComplete();
            }
        });


    }

    private DataItemDetail mAccountInfo;

    @Override
    protected void initViewData() {
        userId = GTConfig.instance().mCurName;//android IOS统一用登录账户作为关注的参数-可是-如果是模拟账户，这个值又会发生变化。
//        userId = GTConfig.instance().mCurLoginPhone;// 这是登录用的电话，如果改为用电话作为参数，必须通知IOS一起改
        if (myConcernRequest == null) {
            myConcernRequest = new MyConcernRequest();
        }

        //如果是模拟用户登录，那么，查询当前模拟用户是否关联了真实用户
        //如果关联了，那么就显示真实用户的 “我的关注”; 否则，就显示所有分析师
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_DEMO) {
            int mSeq = GTSDataListener.curSeq++;
            String loginPass = GTConfig.instance().mUserPwd;
            mAccountInfo = DataManager.instance().mAccount;
            String loginPhoneNo = mAccountInfo.getString(GTSConst.JSON_KEY_PHONE);
            if (!StringUtils.isEmpty(loginPhoneNo)) {
                if (loginPhoneNo.startsWith("86")) {
                    loginPhoneNo = loginPhoneNo.substring(2, loginPhoneNo.length());
                }
            }
            Log.d("checkDemoTagParam", "" + mSeq + " - " + loginPhoneNo + "-" + loginPass);
            PhoneLoginPresenter.instance().PhoneLoginFun(AppContances.NORMALREQ_TYPE_GET_CUSTOMERBYMOBILE, mSeq, loginPhoneNo, loginPass,
                    new PhoneLoginPresenter.OnMobileReqResultListener() {
                        @Override
                        public void reqResultSuccess(Object mObject) {
                            JSONObject obj = (JSONObject) mObject;
                            JSONObject result = obj.optJSONObject("result");
                            if (!result.isNull("customerNumber") && !result.isNull("demoCustomerNumber")) {//就是没有绑定
                                String customerNumber = result.optString("customerNumber");
                                Log.d("checkDemoTag", "当前登录的是模拟账户,已绑定真实帐户:" + customerNumber);

                                //如果已经绑定了真实账户，那就让我的关注显示 真实账户的关注数据
                                getFollowedAnalyst(customerNumber);
                            } else {
                                Log.d("checkDemoTag", "当前登录的是模拟账户并且没有绑定真实账户");
                                //如果没有绑定，那就显示所有分析师
                                getAllAnalyst();
                            }
                        }

                        @Override
                        public void reqResultFail(int failCode) {
                            Log.d("checkDemoTag", "请求失败");
                        }
                    });
        } else {
            getFollowedAnalyst(userId);
        }

    }

    /**
     * 加载当前用户已经关注的分析师列表
     */
    private void getFollowedAnalyst(String userId) {
        Log.d("MyConcernActivity", "默认获取用户关注的分析师");
        Log.d("cancelFollowClicked", "现在重新获取用户关注的分析师：");
        myConcernRequest.getFollowedAnalystList(userId, new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                recycler_view.refreshComplete();
                if (result == null || result.size() == 0) {//如果列表为空
                    Log.d("cancelFollowClicked", "用户关注的分析师是空,开始加载所有分析师");
                    getAllAnalyst();//就加载所有分析师列表
                } else {
                    Log.d("cancelFollowClicked", "用户关注的分析师不是空,开始加载用户关注的分析师:size=" + result.size());
                    refreshUi(result, true); //如果列表不是空，就显示这个列表，（不显示checkBox，并且允许左滑）;
                    ifFirstLoadDataFinished = true;
                }
            }

            @Override
            public void onFailure(Exception e) {
                recycler_view.refreshComplete();
                Log.d("getFollowedAnalyst", "Exception:" + e.getLocalizedMessage());
                new ToastPopWindow(MyConcernActivity.this, "服务器错误").show();
            }
        });
    }

    /**
     *
     */
    private void getAllAnalyst() {//显示checkBox并且不允许左滑
        Log.d("MyConcernActivity", "发现用户关注的分析师列表是空，现在开始获取全部分析师");
        myConcernRequest.getAllAnalystList(new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                recycler_view.refreshComplete();
                refreshUi(result, false);//获取全部分析师，是不允许滑动的，只允许点checkbox
                ifFirstLoadDataFinished = true;
            }

            @Override
            public void onFailure(Exception e) {
                recycler_view.refreshComplete();
                Log.d("getAllAnalyst", "Exception:" + e.getLocalizedMessage());
            }
        });
    }

    private void setFollow(final String userId, final String analystNo, int ifFollow, final boolean ifQuickConcern) {

        //判定当前是不是真实用户
        if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {//如果不是真实用户
            new ToastPopWindow(this, getString(R.string.home_discuss_not_real_4)).show();
            return;
        }

        final String s = (ifFollow == MyConcernRequest.CONST_ADD_FOLLOW) ? "关注" : "取消";
        myConcernRequest.addOrRemoveFollowedAnalystList(userId, analystNo, ifFollow, new HttpCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if ("true".equals(result)) {
                    if (ifQuickConcern && !isNotificationEnabled(MyConcernActivity.this)) {//检查用户是否打开了app的系统通知//是否开启通知，并不影响请求的提交
                        showDialog();
                    } else {
                        new ToastPopWindow(MyConcernActivity.this, s + "成功").show();
                    }
                } else {
                    new ToastPopWindow(MyConcernActivity.this, s + "失败").show();
                }
                getFollowedAnalyst(userId);
            }

            @Override
            public void onFailure(Exception e) {
                Log.d("setFollow", "Exception:" + e.getLocalizedMessage());
                new ToastPopWindow(MyConcernActivity.this, s + "失败").show();
            }
        });
    }

    private String createQuickFollowAnalystString() {
        //还需要创建一个默认的一键关注analystNo 串，用英文逗号分隔
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < analystNoList.size(); i++) {
            sb.append(analystNoList.get(i));
            if (i < analystNoList.size() - 1)
                sb.append(",");
        }
        return sb.toString();
    }


    private List<AnalystData> filterAnalystWithoutAccountNo(List<AnalystData> result) {
        List<AnalystData> finalData = new ArrayList<>();
        if (result == null) return finalData;
        for (int i = 0; i < result.size(); i++) {
            if (!TextUtils.isEmpty(result.get(i).accountNo)) {//如果发现accountNo交易账户不是空，就add
                finalData.add(result.get(i));
            }
        }
        return finalData;
    }

    private void refreshUi(List<AnalystData> list, boolean ifAllowSwip) {
        Log.d("refreshUi", "list.size:" + (list == null ? "0" : list.size()));
        analystNoList.clear();
        if (null == list)
            list = new ArrayList<>();

        // 产品大姐大说，不需要过滤，··好吧，那就不过滤、
        if (!ifAllowSwip)//不允许滑动，就是待关注的，需要过滤;  允许滑动的，就不需要过滤
            list = filterAnalystWithoutAccountNo(list);//过滤掉没有交易账号的分析师

        for (int i = 0; i < list.size(); i++) {
            analystNoList.add(list.get(i).userNo);
        }
        if (adapter == null) {
            adapter = new MyConcernRecyclerViewAdapter(analystDataList, this);//设置Adapter
            adapter.setIfAllowSwipe(ifAllowSwip);
            adapter.setOperatorCallback(new MyConcernRecyclerViewAdapter.OperatorCallback() {
                @Override
                public void centerViewClicked(String analystNo, String userNo) {
                    PackStatis.getToService("clickCards", PackStatis.EventCategory.ME.getValue(), null, null);
                    ActivityManager.showAnalystPage(userNo, analystNo, MyConcernActivity.this);
                }

                @Override
                public void cancelFollowClicked(String analystNo) {
                    Log.d("cancelFollowClicked", "analystNo:" + analystNo);
                    setFollow(userId, analystNo, MyConcernRequest.CONST_CANCEL_FOLLOW, false);
                }

                @Override
                public void analystCheckedChanged(String analystNo, boolean ifChecked) {
                    if (!ifChecked) {//false，新增
                        analystNoList.remove(analystNo);
                    } else {
                        analystNoList.add(analystNo);
                    }
                }

                @Override
                public void quickFollowAnalyst() {//这是在item内部点击 一键关注的时候触发的事件
                    String str = createQuickFollowAnalystString();
                    if (TextUtils.isEmpty(str)) {
                        new ToastPopWindow(MyConcernActivity.this, "您还没有选择要关注的分析师..").show();
                    } else {
                        setFollow(userId, str, MyConcernRequest.CONST_ADD_FOLLOW, true);
                    }
                }
            });
            recycler_view.setAdapter(adapter);
        }
        analystDataList = list;
        adapter.setIfAllowSwipe(ifAllowSwip);
        adapter.setData(list);

    }

    /**
     * 检查当前是否开启了通知权限
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private boolean isNotificationEnabled(Context context) {

        if (Build.VERSION.SDK_INT < 26) {//26 是android8.0，如果是8.0以下，就用这个
            String CHECK_OP_NO_THROW = "checkOpNoThrow";
            String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

            AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            ApplicationInfo appInfo = context.getApplicationInfo();
            String pkg = context.getApplicationContext().getPackageName();
            int uid = appInfo.uid;

            /* Context.APP_OPS_MANAGER */
            try {
                Class<?> appOpsClass = Class.forName(AppOpsManager.class.getName());
                Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
                Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

                int value = (Integer) opPostNotificationValue.get(Integer.class);
                return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            boolean ifOk = NotificationManagerCompat.from(context).areNotificationsEnabled();
            Log.e("ifOk", "" + ifOk);
            return ifOk;
        }

        return true;
    }

    private void showDialog() {
        View root = LayoutInflater.from(this).inflate(R.layout.dialog_myconcern, null, false);
        ImageView iv_close = (ImageView) root.findViewById(R.id.iv_close);
        TextView tv_open_permission = (TextView) root.findViewById(R.id.tv_open_permission);
        final VipDialog alertDialog = new VipDialog(this, 0, 0, root, R.style.VipDialog);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        tv_open_permission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                showTip();
                toNotificationSetting();
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }

    private void showTip() {
        if (mTip == null || mTipClose == null || mTipOpen == null) {
            return;
        }
        mTip.setVisibility(View.VISIBLE);
        mTipClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTip != null) {
                    mTip.setVisibility(View.GONE);
                    CacheUtils.writeFile(CacheUtils.CACHE_SHOW_NOTICE_TIP, "已经手动关闭");
                }
            }
        });
        mTipOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toNotificationSetting();
            }
        });
    }

    private void hideTip() {
        if (mTip == null || mTipClose == null || mTipOpen == null) {
            return;
        }
        mTip.setVisibility(View.GONE);
    }

    private void toNotificationSetting() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", BuildConfig.APPLICATION_ID, null));
        if (localIntent.resolveActivity(AppMain.getApp().getPackageManager()) != null) {
            startActivity(localIntent);
        }
    }

    @Override
    public void onRefresh() {
        initViewData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        hideTip();
        if (ifFirstLoadDataFinished) {// 如果首次加载数据已结束
            initViewData();
        }
    }
}
